'''
OpenMV搭配ATWINC1500 WiFi模块，实现获取B站粉丝数的例程

展现联网获取HTTP网页的功能
同样还可以获取时间、天气等

bilibili@程欢欢的智能控制集
20230826
'''
import network, usocket, ussl, re

# 需要修改的部分：
SSID ='LL-Love'     # 无线网络名
KEY  ='06150407'       # 无线网络密码
bilibili_ID ='1900950532'   #B站ID

# HTTPS Info
HOST = "api.bilibili.com"
PORT = 443  # HTTPS 默认端口

# 初始化 WLAN 模块并连接到网络
print("Trying to connect... (may take a while)...")
wlan = network.WINC()
wlan.connect(SSID, key=KEY, security=wlan.WPA_PSK)

# 通过 DHCP 获取有效的 IP 地址
print(wlan.ifconfig())

while True:
    # 通过 DNS 获取地址信息
    addr_info = usocket.getaddrinfo(HOST, PORT)
    addr = addr_info[0][-1]

    # 创建一个新的 socket 并连接到地址
    client_sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
    client_sock.connect(addr)

    # 将普通 socket 封装为 SSL socket
    secure_sock = ussl.wrap_socket(client_sock, server_hostname=HOST)

    # 发送 HTTP 请求并接收响应
    secure_sock.write("GET /x/relation/stat?vmid="+bilibili_ID+" HTTP/1.1\r\nHost: {}\r\n\r\n".format(HOST))
    response = secure_sock.read(1024)

    # 打印响应
    #print(response)    #打印完整的网页信息
    # 假设 response 是你获取的 HTTP 响应
    response_str = response.decode("utf-8")  # 将字节串解码为字符串

    # 查找 "follower" 字段和其数值
    start_index = response_str.find('"follower":') + len('"follower":')

    # 提取数值
    follower_count = int(response_str[start_index:-2])
    print("粉丝数:", follower_count)

    # 关闭 socket
    secure_sock.close()
    client_sock.close()
